#include <iostream>
#include <limits>
#include <vector>
#include <map>
#include <list>

#include <Windows.h>
#include "File.h"
#include "Directory.h"
#include "FileDuplicates.h"
#include "MyTimer.h"

#include <io.h>
#include <fcntl.h>
using namespace std;


int main(int i_argc, char* i_argv[])
  {
  wstring dir;
  
  // setting console output for unicode
  int io_r = _setmode(_fileno(stdout), _O_U16TEXT);
  if (io_r < 0)
    {
    cout << "FAILED" << endl;
    return 0;
    }
  if (i_argc > 1)
    {
    dir = (const wchar_t*)i_argv[1];
    }
  else
    {
    wcout << "Input directory: " << endl << " > ";
    wcin >> dir;
    }

  Directory d(dir);
  if (d.IsValid() == false)
    {
    wcout << "Invalid directory!" << endl;
    return 0;
    }
  wcout << "Pre-scanning directory..." << endl;
  wcout << "Directory size: " << d.GetSize() << " bytes" << endl;

  // searching for duplicates
  FileDuplicates fd = FileDuplicates(d);

  wcout << endl << "Progress:" << endl;
  _setmode(_fileno(stdout), _O_TEXT);
    {
    MyTimer t;
    fd.Search();
    cout << endl << "TIME ";
    }
  _setmode(_fileno(stdout), _O_U16TEXT);
  map<wstring, list<wstring>> res = fd.GetResult();

  // result output
  if (res.empty())
    {
    wcout << L"NO DUPLICATES FOUND!" << endl;
    size_t fto = fd.GetFailedToOpen();
    wcout << endl << "Failed to open: " << fto << " files." << endl << endl;
    _setmode(_fileno(stdout), _O_TEXT);
    system("pause");
    return 0;
    }

  wcout << endl << endl << L"\tDUPLICATES FOUND:\n";
  int i = 0;
  for (auto& it : res)
    {
    ++i;
    wcout << L"SET " << i << endl;
    wcout << L"\t\t> " <<  it.first << L'\n';
    for (auto& f : it.second)
      wcout << L"\t\t> " <<  f << L'\n';
    wcout << endl;
    }

  size_t fto = fd.GetFailedToOpen();
  wcout << endl << "Failed to open: " << fto << " files." << endl << endl;
  _setmode(_fileno(stdout), _O_TEXT);
  system("pause");
  return 0;
  }